import React, { useEffect, useState } from 'react';
import { 
  Descriptions, Button, Card, Timeline, Tag, Form, Input, DatePicker, Select, 
  message, Popconfirm, Row, Col, Checkbox, InputNumber, Divider, Tabs, Badge 
} from 'antd';
import '../components.css';
import CollectionsService from '../../services/CollectionsService';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { 
  ArrowLeftOutlined, EditOutlined, CheckOutlined, DeleteOutlined,
  ClockCircleOutlined, FileTextOutlined, HistoryOutlined 
} from '@ant-design/icons';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

export default function CollectionDetail() {
  const [collectionData, setCollectionData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [form] = Form.useForm();
  const [selectedPersons, setSelectedPersons] = useState([]);
  
  const location = useLocation();
  const navigate = useNavigate();
  const path = location.pathname;
  const id = path.split('/')[2];

  const persons = ['Jessie', 'Michael', 'Amanda', '陈小红', '曾小芳'];
  const approvalHistory = [
    { time: '2019-03-23 22:31', operator: 'Michael', action: '否决了第1期回款审批', reason: '原因备注：无', relatedOrder: '来自订单: 订单标题' },
    { time: '2019-03-22 14:15', operator: 'Jessie', action: '提交了回款审批', reason: '', relatedOrder: '来自订单: 订单标题' }
  ];

  useEffect(() => {
    fetchCollectionData();
  }, [id]);

  const fetchCollectionData = () => {
    setLoading(true);
    CollectionsService.getCollectionById(id)
      .then(response => {
        const data = response.data;
        setCollectionData(data);
        form.setFieldsValue({
          ...data,
          collectionDate: moment(data.collectionDate),
        });
        setLoading(false);
      })
      .catch(error => {
        console.log(error);
        setLoading(false);
      });
  };

  const handleEdit = () => setIsEditing(true);

  const handleSave = () => {
    form.validateFields()
      .then(values => {
        const formattedValues = {
          ...values,
          collectionDate: values.collectionDate.format('YYYY-MM-DD'),
          id: collectionData.id, // 确保包含ID
          orderId: values.orderId || collectionData.orderId, // 保留原始值如果不存在
        };
        
        CollectionsService.updateCollection(id, formattedValues)
          .then(() => {
            message.success('更新成功！');
            setIsEditing(false);
            fetchCollectionData();
          })
          .catch(error => {
            console.log(error);
            message.error('更新失败: ' + (error.response?.data?.message || error.message));
          });
      })
      .catch(err => {
        console.log('Validation failed:', err);
      });
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    form.resetFields();
    setSelectedPersons([]);
  };

  const handleSubmitApproval = () => {
    CollectionsService.updateCollection(id, { ...collectionData, approvalStatus: '待审批' })
      .then(() => {
        message.success('已提交审批！');
        fetchCollectionData();
      })
      .catch(error => {
        console.log(error);
        message.error('提交审批失败');
      });
  };

  const handleDelete = () => {
    CollectionsService.deleteCollection(id)
      .then(() => {
        message.success('删除成功！');
        navigate('/collectionlist');
      })
      .catch(error => {
        console.log(error);
        message.error('删除失败');
      });
  };

  const getApprovalStatusColor = (status) => {
    switch (status) {
      case '已通过': return 'green';
      case '被否决': 
      case '被驳回': return 'red';
      case '已撤销': return 'orange';
      default: return 'blue';
    }
  };

  if (loading) return <div className='loading-container'>加载中...</div>;
  if (!collectionData) return <div className='error-container'>数据加载失败</div>;

  return (
    <div className='collection-detail-container'>
      <div className="page-header">
        <Button type="link" icon={<ArrowLeftOutlined />} onClick={() => navigate('/collectionlist')}>
          返回列表
        </Button>
        <span className="page-title">
          第{collectionData.period.replace('第', '').replace('期', '')}期回款
        </span>
        <Tag 
          color={getApprovalStatusColor(collectionData.approvalStatus)} 
          className="status-tag"
        >
          {collectionData.approvalStatus}
        </Tag>
        
        <div className="action-buttons">
          {isEditing ? (
            <>
              <Button type="primary" icon={<CheckOutlined />} onClick={handleSave} style={{ marginRight: 8 }}>
                保存
              </Button>
              <Button onClick={handleCancelEdit}>取消</Button>
            </>
          ) : (
            <>
              <Button 
                type="primary" 
                icon={<EditOutlined />} 
                onClick={handleEdit}
                style={{ marginRight: 8 }}
                disabled={collectionData.approvalStatus === '已通过'}
              >
                编辑
              </Button>
              <Button 
                type="primary" 
                ghost
                onClick={handleSubmitApproval}
                style={{ marginRight: 8 }}
                disabled={collectionData.approvalStatus === '已通过' || collectionData.approvalStatus === '待审批'}
              >
                提交审批
              </Button>
              <Popconfirm
                title="确定删除此回款记录吗?"
                onConfirm={handleDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button 
                  danger 
                  icon={<DeleteOutlined />}
                  disabled={collectionData.approvalStatus === '已通过'}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          )}
        </div>
      </div>

      <Card className="main-content-card" bordered={false}>
        {isEditing ? (
          <Form form={form} layout="vertical">
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item label="关联订单ID" name="orderId" rules={[{ required: true, message: '请输入关联订单ID!' }]}>
                  <Input placeholder="请输入8位订单ID" />
                </Form.Item>

                <Form.Item label="回款日期" name="collectionDate" rules={[{ required: true, message: '请选择回款日期!' }]}>
                  <DatePicker style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item label="回款期次" name="period" rules={[{ required: true, message: '请输入回款期次!' }]}>
                  <Input placeholder="例：第1期" />
                </Form.Item>

                <Form.Item label="回款金额" name="amount" rules={[{ required: true, message: '请输入回款金额!' }]}>
                  <InputNumber 
                    prefix="¥" 
                    style={{ width: '100%' }} 
                    min={0}
                    step={100}
                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="付款方式" name="paymentMethod" rules={[{ required: true, message: '请选择付款方式!' }]}>
                  <Select>
                    <Option value="现金">现金</Option>
                    <Option value="银行转账">银行转账</Option>
                    <Option value="支付宝">支付宝</Option>
                    <Option value="微信支付">微信支付</Option>
                  </Select>
                </Form.Item>

                <Form.Item label="审批状态" name="approvalStatus" rules={[{ required: true, message: '请选择审批状态!' }]}>
                  <Select>
                    <Option value="待审批">待审批</Option>
                    <Option value="已通过">已通过</Option>
                    <Option value="被否决">被否决</Option>
                    <Option value="被驳回">被驳回</Option>
                    <Option value="已撤销">已撤销</Option>
                  </Select>
                </Form.Item>

                <Form.Item label="逾期状态" name="overdueStatus" rules={[{ required: true, message: '请选择逾期状态!' }]}>
                  <Select>
                    <Option value="正常">正常</Option>
                    <Option value="逾期">逾期</Option>
                    <Option value="部分逾期">部分逾期</Option>
                  </Select>
                </Form.Item>

                <Form.Item label="备注信息" name="remark">
                  <TextArea rows={4} placeholder="请输入备注信息" maxLength={300} />
                </Form.Item>
              </Col>
            </Row>

            <Card title="通知人员" className="notification-card">
              <Checkbox.Group 
                options={persons} 
                onChange={setSelectedPersons}
                value={selectedPersons}
              />
              <div className="notification-hint">
                注：审批完成后，将自动通知到所选人员。
              </div>
            </Card>
          </Form>
        ) : (
          <Tabs defaultActiveKey="1">
            <TabPane tab={<span><FileTextOutlined />基本信息</span>} key="1">
              <Row gutter={24}>
                <Col span={12}>
                  <Descriptions column={1} bordered className="info-descriptions">
                    <Descriptions.Item label="回款日期">{collectionData.collectionDate}</Descriptions.Item>
                    <Descriptions.Item label="关联订单">{collectionData.orderId}</Descriptions.Item>
                    <Descriptions.Item label="回款期次">{collectionData.period}</Descriptions.Item>
                    <Descriptions.Item label="付款方式">{collectionData.paymentMethod}</Descriptions.Item>
                  </Descriptions>
                </Col>
                <Col span={12}>
                  <Descriptions column={1} bordered className="info-descriptions">
                    <Descriptions.Item label="系统编号">{collectionData.id}</Descriptions.Item>
                    <Descriptions.Item label="回款金额">¥ {parseFloat(collectionData.amount).toFixed(2)}</Descriptions.Item>
                    <Descriptions.Item label="审批状态">{collectionData.approvalStatus}</Descriptions.Item>
                    <Descriptions.Item label="逾期状态">{collectionData.overdueStatus}</Descriptions.Item>
                  </Descriptions>
                </Col>
              </Row>
            </TabPane>

            <TabPane tab={<span><HistoryOutlined />审批动态</span>} key="2">
              <Timeline mode="left" className="approval-timeline">
                {approvalHistory.map((item, index) => (
                  <Timeline.Item 
                    key={index} 
                    label={item.time}
                    color={index === 0 ? "red" : "blue"}
                    dot={index === 0 ? <ClockCircleOutlined style={{ fontSize: '16px' }} /> : null}
                  >
                    <div className="timeline-content">
                      <div className="operator">{item.operator}</div>
                      <div className="action">{item.action} {item.reason}</div>
                      <div className="related-order">{item.relatedOrder}</div>
                    </div>
                  </Timeline.Item>
                ))}
              </Timeline>
            </TabPane>
          </Tabs>
        )}
      </Card>
    </div>
  );
}